// pages/teacher/kaoqin/kaoqin.js
Page({
  data: {
    currentDate: '',
    courseList: [
      { id: 0, name: '全部课程' }
    ],
    courseIndex: 0,
    statusList: ['全部', '进行中', '已完成'],
    statusIndex: 0,
    attendanceList: [],
    attendanceStats: {
      total: 0,
      ongoing: 0,
      completed: 0,
      rate: '0%'
    },
    isLoading: false,
    // 添加请假和通知的计数
    leaveCount: 3,
    notificationCount: 2
  },

  // 修改考勤管理页面的代码，确保正确显示班级人数
  
  // 在页面加载时获取班级人数
  onLoad: function() {
    // 设置当前日期
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    
    this.setData({
      currentDate: `${year}-${month}-${day}`
    });
    
    // 获取教师课程列表
    this.fetchCourseList();
    
    // 不在onLoad中调用fetchAttendanceList，避免与onShow重复调用
  },
  
  onShow: function() {
    // 页面显示时刷新数据
    this.fetchAttendanceList();
  },
  
  // 获取教师课程列表
  fetchCourseList: function() {
    const userInfo = wx.getStorageSync('userInfo');
    const userId = userInfo.userId || userInfo.id;
    
    wx.request({
      url: 'http://localhost:3000/api/teacher/courses',
      method: 'GET',
      data: {
        userId: userId
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('课程列表响应:', res.data);
        
        if (res.statusCode === 200 && res.data.success) {
          // 确保返回的数据是数组
          let courses = res.data.data || [];
          
          // 检查返回的数据结构
          if (!Array.isArray(courses)) {
            if (res.data.courses && Array.isArray(res.data.courses)) {
              courses = res.data.courses;
            } else {
              courses = [];
            }
          }
          
          // 处理字段名不匹配问题，将courseId映射为id，courseName映射为name
          const mappedCourses = courses.map(course => {
            return {
              id: course.id || course.courseId,
              name: course.name || course.courseName,
              courseId: course.courseId,
              courseName: course.courseName,
              classId: course.classId,
              className: course.className,
              // 保留其他原始字段
              ...course
            };
          });
          
          // 添加"全部课程"选项
          const allCourses = [{ id: 0, name: '全部课程' }, ...mappedCourses];
          
          this.setData({
            courseList: allCourses
          });
          
          console.log('处理后的课程列表:', allCourses);
        } else {
          wx.showToast({
            title: res.data.message || '获取课程列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取课程列表失败:', err);
        wx.showToast({
          title: '获取课程列表失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 日期变更
  dateChange: function(e) {
    this.setData({
      currentDate: e.detail.value,
      attendanceList: []
    });
    
    this.fetchAttendanceList();
  },
  
  // 课程变更
  courseChange: function(e) {
    this.setData({
      courseIndex: e.detail.value,
      attendanceList: []
    });
    
    this.fetchAttendanceList();
  },
  
  // 状态变更
  statusChange: function(e) {
    this.setData({
      statusIndex: e.detail.value,
      attendanceList: []
    });
    
    this.fetchAttendanceList();
  },
  
  // 获取考勤列表
  fetchAttendanceList: function() {
    this.setData({
      isLoading: true
    });
    
    // 获取用户ID
    const userInfo = wx.getStorageSync('userInfo');
    const userId = userInfo.userId || userInfo.id;
    
    // 构建请求参数 - 使用userId而不是teacherId
    const params = {
      userId: userId,  // 修改为userId，与后端接口匹配
      date: this.data.currentDate
    };
    
    // 只有当选择了非"全部"的课程时才添加courseId参数
    if (this.data.courseIndex > 0 && this.data.courseList[this.data.courseIndex]) {
      params.courseId = this.data.courseList[this.data.courseIndex].id;
    }
    
    // 只有当选择了非"全部"的状态时才添加status参数
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusList[this.data.statusIndex];
    }
    
    console.log('获取考勤列表参数:', params);
    
    // 获取考勤列表
    wx.request({
      url: 'http://localhost:3000/api/teacher/attendance-sessions',
      method: 'GET',
      data: params,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('考勤列表响应:', res.data);
        
        if (res.statusCode === 200 && res.data.success) {
          // 处理每个考勤会话，获取实际班级人数
          const sessions = res.data.sessions || [];
          
          // 如果没有考勤会话，直接更新UI
          if (sessions.length === 0) {
            this.setData({
              attendanceList: [],
              attendanceStats: res.data.stats || {
                total: 0,
                ongoing: 0,
                completed: 0,
                rate: '0%'
              },
              isLoading: false
            });
            return;
          }
          
          // 为每个会话获取班级统计数据
          const promises = sessions.map(session => {
            return new Promise((resolve) => {
              // 修改前端调用路径
              wx.request({
                url: 'http://localhost:3000/api/attendance/class-stats', 
                method: 'GET',
                data: {
                  classId: session.classId,
                  courseId: session.courseId,
                  sessionId: session.id, // 添加sessionId参数
                  date: session.date || this.data.currentDate
                },
                header: {
                  'Authorization': 'Bearer ' + wx.getStorageSync('token')
                },
                success: (statsRes) => {
                  console.log('班级统计响应:', statsRes.data);
                  
                  if (statsRes.statusCode === 200 && statsRes.data.success) {
                    // 更新会话的统计数据，处理可能的字段名不一致问题
                    const stats = statsRes.data.stats || {};
                    session.totalCount = stats.total || 0;
                    // 检查多个可能的字段名
                    session.presentCount = stats.checkedIn || stats.present || stats.attendance || 0;
                    session.absentCount = stats.absent || (stats.total - (stats.checkedIn || stats.present || 0)) || 0;
                    session.leaveCount = stats.leave || 0;
                    
                    console.log('处理后的会话数据:', session);
                  }
                  resolve(session);
                },
                fail: () => {
                  resolve(session);
                }
              });
            });
          });
          
          // 等待所有请求完成后更新UI
          Promise.all(promises).then(updatedSessions => {
            this.setData({
              attendanceList: updatedSessions,
              attendanceStats: res.data.stats || {
                total: 0,
                ongoing: 0,
                completed: 0,
                rate: '0%'
              },
              isLoading: false
            });
          });
        } else {
          this.setData({
            attendanceList: [],
            isLoading: false
          });
          
          wx.showToast({
            title: res.data.message || '获取考勤列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取考勤列表失败:', err);
        this.setData({
          isLoading: false
        });
        wx.showToast({
          title: '获取考勤列表失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 查看考勤详情
  viewAttendanceDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/teacher/kaoqin/detail/detail?id=${id}`
    });
  },
  
  // 修改考勤信息（复用详情页面）
  editAttendance: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/teacher/kaoqin/detail/detail?id=${id}`
    });
  },
  
  // 发起考勤
  startAttendance: function() {
    wx.navigateTo({
      url: '/pages/teacher/kaoqin/faqi/faqi'
    });
  },
  
  // 查看考勤统计
  viewStatistics: function() {
    wx.navigateTo({
      url: '/pages/teacher/kaoqin/tongji/tongji'
    });
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.fetchAttendanceList();
  },
  
  // 查看请假申请
  viewLeaveRequests: function() {
    wx.navigateTo({
      url: '/pages/teacher/qingjia/qingjia'
    });
  },
  
  // 查看消息通知（新增）
  viewNotifications: function() {
    wx.navigateTo({
      url: '/pages/teacher/xiaoxi/xiaoxi'
    });
  },
  
  // 切换考勤状态（新增）
  toggleAttendanceStatus: function(e) {
    const id = e.currentTarget.dataset.id;
    const currentStatus = e.currentTarget.dataset.status;
    const newStatus = currentStatus === '进行中' ? '已完成' : '进行中';
    
    // 将前端状态转换为数据库状态
    const dbStatus = newStatus === '进行中' ? 'active' : 'closed';
    
    wx.showLoading({
      title: '更新状态中...'
    });
    
    wx.request({
      url: `http://localhost:3000/api/teacher/attendance/${id}/status`,
      method: 'PUT',  // 使用PUT方法
      data: {
        status: dbStatus  // 发送数据库格式的状态
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200 && res.data.success) {
          // 更新本地数据
          const attendanceList = this.data.attendanceList.map(item => {
            if (item.id === id) {
              item.status = newStatus;
            }
            return item;
          });
          
          this.setData({
            attendanceList: attendanceList
          });
          
          wx.showToast({
            title: '状态已更新',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.message || '更新状态失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('更新状态失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 快速发起考勤
  startQuickAttendance: function() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    // 获取当前选中的课程
    const selectedCourse = this.data.courseList[this.data.courseIndex];
    
    if (!selectedCourse || !selectedCourse.id || selectedCourse.id === 0) {
      wx.showToast({
        title: '请先选择课程',
        icon: 'none'
      });
      return;
    }
    
    // 确保classId存在
    if (!selectedCourse.classId) {
      wx.showToast({
        title: '课程未关联班级',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载提示
    wx.showLoading({
      title: '发起考勤中...'
    });
    
    // 获取位置信息
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        // 先获取班级人数
        wx.request({
          url: 'http://localhost:3000/api/attendance/class-stats',
          method: 'GET',
          data: {
            classId: selectedCourse.classId,
            courseId: selectedCourse.id
          },
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: (statsRes) => {
            console.log('班级统计响应:', statsRes.data);
            
            // 调用后端接口发起考勤
            wx.request({
              url: 'http://localhost:3000/api/teacher/start-session', // 修改为教师接口
              method: 'POST',
              header: {
                'Authorization': 'Bearer ' + wx.getStorageSync('token'),
                'Content-Type': 'application/json'
              },
              data: {
                userId: userInfo.userId || userInfo.id,
                courseId: selectedCourse.id,
                classId: selectedCourse.classId,
                // 设置位置信息，确保所有值都有默认值
                locationRequired: true,
                validDistance: 100,
                latitude: res.latitude || 0,
                longitude: res.longitude || 0,
                address: '教学楼'
              },
              success: (res) => {
                wx.hideLoading();
                console.log('发起考勤响应:', res.data);
                
                if (res.statusCode === 201 && res.data.success) {
                  // 获取班级人数统计
                  const stats = statsRes.data.success ? statsRes.data.stats : {
                    total: 0,
                    checkedIn: 0,
                    absent: 0,
                    leave: 0
                  };
                  
                  // 创建新的考勤记录并添加到列表
                  const now = new Date();
                  const newAttendance = {
                    id: res.data.sessionId,
                    courseName: selectedCourse.name,
                    className: selectedCourse.className || '未知班级',
                    date: now.toISOString().split('T')[0],
                    time: now.toTimeString().split(' ')[0],
                    location: '教学楼',
                    type: '定位签到',
                    status: '进行中',
                    totalCount: stats.total,
                    presentCount: 0,
                    absentCount: stats.total,
                    leaveCount: 0
                  };
                  
                  // 更新考勤列表
                  const attendanceList = [newAttendance, ...this.data.attendanceList];
                  this.setData({
                    attendanceList: attendanceList
                  });
                  
                  wx.showToast({
                    title: '签到已发起',
                    icon: 'success'
                  });
                } else {
                  wx.showToast({
                    title: res.data.message || '发起签到失败',
                    icon: 'none'
                  });
                }
              },
              fail: (err) => {
                wx.hideLoading();
                console.error('发起签到失败:', err);
                wx.showToast({
                  title: '网络错误',
                  icon: 'none'
                });
              }
            });
          },
          fail: (err) => {
            wx.hideLoading();
            console.error('获取班级统计失败:', err);
            wx.showToast({
              title: '获取班级信息失败',
              icon: 'none'
            });
          }
        });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
      }
    });
  }
});